"""
审计日志服务
创建时间：2025-09-17
作者：开发团队
目的：处理审计日志相关业务逻辑
"""

from sqlalchemy.orm import Session
from sqlalchemy import desc
from datetime import datetime
from ..models.audit_log import AuditLog
from ..models.user import User
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)


def create_audit_log(
    db: Session,
    user_id: int,
    action_type: str,
    target_type: str | None = None,
    target_id: int | None = None,
    detail: str | None = None,
    ip_address: str | None = None
) -> AuditLog:
    """
    创建审计日志记录
    :param db: 数据库会话
    :param user_id: 用户ID
    :param action_type: 操作类型
    :param target_type: 目标类型
    :param target_id: 目标ID
    :param detail: 详细信息
    :param ip_address: IP地址
    :return: 创建的审计日志记录
    """
    try:
        audit_log = AuditLog(
            user_id=user_id,
            action_type=action_type,
            target_type=target_type,
            target_id=target_id,
            detail=detail,
            ip_address=ip_address
        )
        db.add(audit_log)
        db.commit()
        db.refresh(audit_log)
        logger.info(f"创建审计日志记录: user_id={user_id}, action={action_type}")
        return audit_log
    except Exception as e:
        db.rollback()
        logger.error(f"创建审计日志记录失败: {str(e)}")
        raise


def get_audit_logs(
    db: Session,
    skip: int = 0,
    limit: int = 100,
    user_id: int | None = None,
    action_type: str | None = None,
    start_date: datetime | None = None,
    end_date: datetime | None = None
) -> list[AuditLog]:
    """
    获取审计日志列表
    :param db: 数据库会话
    :param skip: 跳过的记录数
    :param limit: 返回的记录数
    :param user_id: 用户ID筛选
    :param action_type: 操作类型筛选
    :param start_date: 开始日期筛选
    :param end_date: 结束日期筛选
    :return: 审计日志列表
    """
    try:
        query = db.query(AuditLog).join(User)
        
        # 添加筛选条件
        if user_id:
            query = query.filter(AuditLog.user_id == user_id)
        if action_type:
            query = query.filter(AuditLog.action_type == action_type)
        if start_date:
            query = query.filter(AuditLog.created_at >= start_date)
        if end_date:
            query = query.filter(AuditLog.created_at <= end_date)
            
        # 按创建时间倒序排列
        audit_logs = query.order_by(desc(AuditLog.created_at)).offset(skip).limit(limit).all()
        logger.info(f"获取审计日志列表: {len(audit_logs)} 条记录")
        return audit_logs
    except Exception as e:
        logger.error(f"获取审计日志列表失败: {str(e)}")
        raise


def get_audit_log_by_id(db: Session, log_id: int) -> AuditLog | None:
    """
    根据ID获取审计日志记录
    :param db: 数据库会话
    :param log_id: 审计日志ID
    :return: 审计日志记录或None
    """
    try:
        audit_log = db.query(AuditLog).filter(AuditLog.id == log_id).first()
        return audit_log
    except Exception as e:
        logger.error(f"根据ID获取审计日志记录失败: {str(e)}")
        raise


def delete_audit_log(db: Session, log_id: int) -> bool:
    """
    删除审计日志记录
    :param db: 数据库会话
    :param log_id: 审计日志ID
    :return: 删除是否成功
    """
    try:
        audit_log = db.query(AuditLog).filter(AuditLog.id == log_id).first()
        if audit_log:
            db.delete(audit_log)
            db.commit()
            logger.info(f"删除审计日志记录: id={log_id}")
            return True
        return False
    except Exception as e:
        db.rollback()
        logger.error(f"删除审计日志记录失败: {str(e)}")
        raise


def get_audit_log_count(
    db: Session,
    user_id: int | None = None,
    action_type: str | None = None,
    start_date: datetime | None = None,
    end_date: datetime | None = None
) -> int:
    """
    获取审计日志总数
    :param db: 数据库会话
    :param user_id: 用户ID筛选
    :param action_type: 操作类型筛选
    :param start_date: 开始日期筛选
    :param end_date: 结束日期筛选
    :return: 审计日志总数
    """
    try:
        query = db.query(AuditLog)
        
        # 添加筛选条件
        if user_id:
            query = query.filter(AuditLog.user_id == user_id)
        if action_type:
            query = query.filter(AuditLog.action_type == action_type)
        if start_date:
            query = query.filter(AuditLog.created_at >= start_date)
        if end_date:
            query = query.filter(AuditLog.created_at <= end_date)
            
        count = query.count()
        logger.info(f"获取审计日志总数: {count}")
        return count
    except Exception as e:
        logger.error(f"获取审计日志总数失败: {str(e)}")
        raise